package com.jty.module_main.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.jty.module_main.BR
import com.jty.module_main.R
import com.jty.lib_base.data.bean.BookNoteBean
import com.jty.lib_base.utils.MultiClickUtil
import com.jty.module_main.databinding.MainNoteItemVBinding


class NoteBookAdapter(val mContext: Context): RecyclerView.Adapter<NoteBookAdapter.Companion.ViewHolder>(){
    var mData : List<BookNoteBean>? = null

    fun refreshData(counts: List<BookNoteBean>?) {
        mData = counts
        notifyDataSetChanged()
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val layoutInflater =LayoutInflater.from(parent.context)
        val binding : MainNoteItemVBinding = MainNoteItemVBinding.inflate(layoutInflater, parent, false)
        val holder:ViewHolder  = ViewHolder(binding.getRoot())
        holder.binding = binding
        return holder;
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.setVariable(BR.viewModel, mData?.get(position))

        Glide.with(mContext)
            .load(mData?.get(position)?.coverUrl)
            .error(R.drawable.ic_avatar_black)
            .placeholder(R.drawable.ic_avatar_black)
            .into(holder.binding.ivCover);

        holder.binding.executePendingBindings() //立即刷新UI

        holder.itemView.setOnClickListener {
            if(MultiClickUtil.isFastClick())
                onItemClickListener?.onItemClick(holder.itemView,position, mData?.get(position)?.id!!
                    , mData?.get(position)!!.lastPage?:0, mData?.get(position)!!.name?:"", mData?.get(position)!!.pageNum?:0)
        }

    }

    override fun getItemCount(): Int {
        return mData?.size?:0
    }

    companion object{
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            lateinit var binding: MainNoteItemVBinding
        }
    }

    //  增加点击和长按事件
    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int, id: Int, lastIndex:Int, bookName:String, totalPage:Int)
//        fun onItemLongClick(view: View,position: Int): Boolean
    }

    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }
}